package edu.ufl.cise.sanitas.client;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import edu.ufl.cise.sanitas.client.proxy.Proxy;
import edu.ufl.cise.sanitas.types.comm.QueryAllConditionsRequest;
import edu.ufl.cise.sanitas.types.comm.QueryAllConditionsResponse;
import edu.ufl.cise.sanitas.types.comm.Response;
import edu.ufl.cise.sanitas.types.comm.UpdateUserConditionsRequest;

public class Profile extends Activity {
	
	private static final int MESSAGECODE_QUERYALLCONDS = 0;
	private static final int MESSAGECODE_UPDATEUSERCONDITIONS = 1;
	private static final int RETURN_ID = 0;

	private String[] conditionList = null;
	private boolean[] checkList = null;
	
	private Handler updateUserConditionsHandler = new Handler() {
		
		@Override
		public void handleMessage(Message msg) {
			Response r = (Response) msg.obj;
			switch (r.getStatus()) {
			case SUCCESS:
				pd.dismiss();
				break;
			case FAIL:
			case TIMEOUT:
				AlertDialog.Builder timeoutBuilder = new AlertDialog.Builder(mCtx);
				timeoutBuilder.setMessage("Sorry! Failed to fetch condition list. Your choices will be updated automatically.")
					.setPositiveButton("OK", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							ad.dismiss();
							Proxy.setUpdateConditionList(true);
						}
						
					});
				ad = timeoutBuilder.create();
				pd.dismiss();
				ad.show();
				break;
			}
		}
		
	};
	
	private Handler queryAllConditionsHandler = new Handler() {
		
		@Override
		public void handleMessage(Message msg) {
			Response r = (Response) msg.obj;
			switch (r.getStatus()) {
			case SUCCESS:
				conditionList = ((QueryAllConditionsResponse) r).getConditionList();
				checkList = new boolean[conditionList.length];
				
				AlertDialog.Builder condDialogBuilder = new AlertDialog.Builder(mCtx);
				condDialogBuilder.setTitle("Pick conditions")
					.setMultiChoiceItems(conditionList, checkList, new OnMultiChoiceClickListener()	{

						@Override
						public void onClick(DialogInterface dialog, int which,
								boolean isChecked) {
							checkList[which] = isChecked;
						}
						
					})
					.setPositiveButton("OK", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							ArrayList<String> condList = new ArrayList<String>();
							int count = 0;
							for (String c : conditionList) {
								if (checkList[count]) condList.add(c);
								++count;
							}
							ad.dismiss();
							pd = ProgressDialog.show(mCtx, "Conditions", "Updating");
							String[] condStringList = new String[condList.size()];
							Proxy.setConditionList(condList.toArray(condStringList));
							mProxy.sendRequest(new UpdateUserConditionsRequest(mProxy.getConnectionStatus(), condList.toArray(condStringList), Proxy.getUser().getName(), Proxy.getUser().getPassword()), updateUserConditionsHandler, MESSAGECODE_UPDATEUSERCONDITIONS);
						}

					});
				
				ad = condDialogBuilder.create();
				
				pd.dismiss();
				
				ad.show();
				
				break;
			case FAIL:
			case TIMEOUT:
				AlertDialog.Builder timeoutBuilder = new AlertDialog.Builder(mCtx);
				timeoutBuilder.setMessage("Sorry! Failed to fetch condition list.")
					.setPositiveButton("OK", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							ad.dismiss();
						}
						
					});
				ad = timeoutBuilder.create();
				pd.dismiss();
				ad.show();
				break;
			}
		}
		
	};

	private SharedPreferences preference;
	private Context mCtx;
	private Proxy mProxy;
	private ProgressDialog pd;
	private AlertDialog ad;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.profile);
		
		mCtx = this;
		mProxy = Proxy.getInstance();
		
		preference = getSharedPreferences("SanitasClient", MODE_PRIVATE);
		
		Button signoutButton = (Button) findViewById(R.id.profile_btn_signout);
		signoutButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				SharedPreferences.Editor editor = preference.edit();
				editor.remove("hasSignin");
				editor.remove("Username");
				editor.remove("UserID");
				editor.remove("Password");
				editor.commit();
				
				Intent i = new Intent();
				setResult(RESULT_CANCELED, i);
				finish();
			}
			
		});
		
		Button conditionButton = (Button) findViewById(R.id.profile_btn_changecondition);
		conditionButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				pd = ProgressDialog.show(mCtx, "All Conditions", "Loading");
				mProxy.sendRequest(new QueryAllConditionsRequest(mProxy.getConnectionStatus()), queryAllConditionsHandler, MESSAGECODE_QUERYALLCONDS);
			}
			
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, RETURN_ID, 0, R.string.mode_menu_return);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case RETURN_ID:
			Intent i = new Intent();
			setResult(RESULT_OK, i);
			finish();
			
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	
}
